<?php
import("ORG.Util.Function");
import("@.Org.Page");
import("ORG.Util.Article");
import("@.Org.Utils");
import("@.Org.ArticleTool");

class ArticleAction extends CommonAction {
  	
	public function _initialize(){
		parent::_initialize();
		$param             =    $this->_get('_URL_');
		$controller        =    $param[0];
		$action            =    $param[1];
		//language
		$lang              =    L($action);
		$mange             =    L('manage');
		
		$this->assign('manage','后台管理');
		$this->assign('lang',$lang);		
		$this->assign('current',$lang);		
	}
		
	/**
	 * Show Articles List Page
	 */
	public function article_list(){				
		// aritlce_filter
		$datas         =    M('ArticleCat')->field("cat_id,cat_name,parent_id,cat_type")->select();	
		$datas         =    $this->catsort($datas,0,0);	
		$articleCatList = array();
		foreach($datas as $n=>$v){
			$v['cat_name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$articleCatList[] =    $v;
		}			
		$this->assign("articleCatList",$articleCatList);
		
		// 取得过滤条件
	    $filter 			= 	array();
	    $sql_article_list 	= 	$this->sql_article_list();
		
		$param = array(
				'result'	=> $sql_article_list,			//分页用的数组或sql
				'listvar'	=> 'articleList',				//分页循环变量
				'listRows'	=> 10,							//每页记录数
				//'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'	=> 'content',	    			//ajax更新内容的容器id，不带#
				'pagesId'	=> 'page',						//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'	=> 'Article:l_article_list',		//ajax更新模板
		);		
		// 分页
		$this->page($param);		
		$this->display("article_list");
	}
	
	/**
	 * 编辑添加文章 : 
	 */
	public function add_article(){		
		// 商品分类	
		$GoodsCatModel	=	new GoodsCatModel();
		$goodsCatList	=	$GoodsCatModel->getCategoryList();
		// 品牌
		$brandList		=	M('Brand')->field("brand_id,brand_name")->select();
		// 文章分类
		$datas			=	M('ArticleCat')->field("cat_id,cat_name,parent_id")->select();
		$datas          =    $this->catsort($datas,0,0);
		$articleCatList = array();
		foreach($datas as $n=>$v){
			$v['cat_name']       =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$articleCatList[]    =    $v;
		}
		$this->assign("goodsCatList",			$goodsCatList);
		$this->assign("brandList",				$brandList);
		$this->assign("articleCatList",			$articleCatList);
		$this->assign("act",					'add_article');
		$this->display();	
	}
	
	/**
	 * 处理添加文章
	 * 
	 */
	public function add_article_ok(){	
	    // 检查是否重复
	    $is_only 	= 	Utils::is_only('article','title', $_POST['title'],0, " cat_id ='$_POST[article_cat]'");		
	    if (!$is_only){
	        //$this->error("文章标题--"  . $_POST['title'] . "--已经存在");
	    }
	    
	    $datas					=	array();	    
	    $datas['cat_id']		=	$_POST['cat_id'];
	    $datas['title']			=	$_POST['title'];
	    //$datas['cat_id']		=	$_POST['cat_id'];
	    $datas['cat_id']		=	$_POST['article_cat'];	   
	    $datas['author']		=	$_POST['author'];
	    $datas['author_email']	=	$_POST['author_email'];
	    $datas['keywords']		=	$_POST['keywords'];
	    $datas['article_type']	=	$_POST['article_type'];
	    $datas['is_open']		=	$_POST['is_open'];
	    $datas['add_time']		=	time();
	    $datas['file_url']		=	$_POST['file_url'];	    
	    $datas['link']			=	empty($_POST['link']) ? '' : $_POST['link'];
	    $datas['description']	=	$_POST['description'];
	    $datas['src']			=	$_POST['src'];
	    $datas['content']		=	$_POST['content'];
	    $datas['open_type']		=	0;	// 默认0: 打开html文件,1：默认打开content字段
	    $datas['sort_order']	=	$_POST['sort_order'];	// 默认0: 打开html文件,1：默认打开content字段
	    // 把html转为html文件存储
	    
	    $dir					=	 "./Public/upload/article/";
	    $ArticleObj            	=    new Article();
	    $ArticleObj->savePath   =    $dir;
		$ArticleObj->saveUrl    =    $dir;	
		
	    $datas	              	=    $ArticleObj->save($datas);
	    
				
	    unset($datas['ctime']);
	    unset($datas['url']);
	    	    
	    if(empty($datas['cat_id'])){
	        $datas['cat_id'] = 0;
	    }
	    /*入库*/ 
	    $article_id				=	M('Article')->add($datas);
	    /*处理关联商品*/ 
	    M('GoodsArticle')->where("article_id = 0")->setField("article_id",$article_id);
	    /*ajax*/     	
	    if($this->isAjax()){	
	    	if($article_id){
	    		 $this->ajaxReturn(1,'操作成功',1);	    		 	
	    	}
	    	else{
	    		$this->ajaxReturn(0,'操作失败',1);
	    	} 	    	
	    }
	    else{
	    	if($article_id){
	    		 $this->success('操作成功');	    		 	
	    	}
	    	else{
	    		$this->error('操作失败');
	    	} 
	    }
	}
	
	/**
	 * 修改文章
	 * Enter description here ...
	 */
	public function mod_article(){
		
		$ArticleModel			=	M('Article');

		/* 文章的信息 */
		$article_id				=	intval($_GET['id']);
		
		if(empty($article_id)){
			$this->redirect('/article/article_list', null, 2,'invalid param , please check the params... ');
		}		
		$article_info			=	$ArticleModel->where("article_id = '{$article_id}'")->find();
		
		$file_path				=	'./Public/Upload/article/' . $article_info['src'];
		$article_content		=	'';	
		if(file_exists($file_path)){
			$article_content	=	file_get_contents($file_path);
		}
		$this->assign('content',$article_content);
		
		/* 文章分类 */
		$datas					=	M('ArticleCat')->field("cat_id,cat_name,parent_id")->select();
		$datas          		=    $this->catsort($datas,0,0);
		$articleCatList 		= 	array();
		foreach($datas as $n=>$v){
			$v['cat_name']      =   str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$articleCatList[]   =   $v;
		}
		
		/* 商品分类 */	
		$GoodsCatModel			=	new GoodsCatModel();
		$goodsCatList			=	$GoodsCatModel->getCategoryList();
		
		/* 文章关联的商品列表 */		
	    $ArticleModel			= 	new ArticleModel();	    
	    $goods_article_list		= 	$ArticleModel->get_article_goods($article_id);
	    
		$this->assign("goodsCatList",			$goodsCatList);
		$this->assign('article_info',			$article_info);
		$this->assign("articleCatList",			$articleCatList);
		$this->assign("goods_article_list",		$goods_article_list);
		$this->assign("act",					'mod_article');
		
		$this->display('Article:add_article');
	}
	
	/**
	 * 处理修改文章
	 * Enter description here ...
	 */
	public function mod_article_ok(){		
		import('@.Plugs.Exchange');		
		$ArticleModel			=	M('Article');		
		$article_id				=	intval($_POST['id']);
		if(empty($article_id)){
			$this->redirect('/article/article_list', null,2,'invalid params , please check the params ...');
		}
		$exc  					= 	new Exchange( "ybr_article", null, 'article_id', 'title');		
	    /* 检查文章名是否相同 */
	    $is_only 				= 	$exc->is_only('title', $_POST['title'], $_POST['id'], "cat_id = '$_POST[article_cat]'");
	
	    if (!$is_only){
	        $this->error( sprintf($_LANG['title_exist'], stripslashes($_POST['title'])) );
	    }		
	    if (empty($_POST['cat_id'])){
	        $_POST['cat_id'] 	= 	0;
	    }
				
	    $Article				=	new Article();
	    $_datas					=	$Article->updateArticles($_POST);
	    	    
	    $datas					=	array();	    
	    $datas['cat_id']		=	$_datas['cat_id'];
	    $datas['title']			=	$_datas['title'];
	    $datas['cat_id']		=	$_datas['article_cat'];	   
	    $datas['author']		=	$_datas['author'];
	    $datas['author_email']	=	$_datas['author_email'];
	    $datas['keywords']		=	$_datas['keywords'];
	    $datas['article_type']	=	$_datas['article_type'];
	    $datas['is_open']		=	$_datas['is_open'];
	    $datas['add_time']		=	time();
	    $datas['file_url']		=	$_datas['file_url'];	    
	    $datas['link']			=	empty($_POST['link']) ? '' : $_POST['link'];
	    $datas['description']	=	$_datas['description'];
	    $datas['src']			=	$_datas['src'];
	    $datas['open_type']		=	0;	// 默认0: 打开html文件,1：默认打开content字段
	    $datas['sort_order']	=	$_datas['sort_order'];	// 默认0: 打开html文件,1：默认打开content字段
	    	    	    
	    if(empty($datas['cat_id'])){
	        $datas['cat_id'] 	= 	0;
	    }	    
	    /* 先删除之前的文章路径 */
	    $src					=	$ArticleModel->where("article_id = '{$article_id}'")->getField('src');	
		
	    if(!empty($src)){
	    	@unlink( "./Public/Upload/" . $src );
	    }	   
		
	    /* 入库  */
	    $ArticleModel->where("article_id = '{$article_id}'")->save($datas);	  

 	    
	    /* 处理关联商品 */
	    M('GoodsArticle')->where("article_id = '0'")->setField("article_id",$article_id);
	    
		$this->ajaxReturn(1,"操作成功",1);
	}
	
	
	/**
	 * 删除文章
	 * 
	 */
	public function del_article(){		
	    $id 		= 	intval($_GET['id']);
	    // 删除原来的文件
//	    $old_url	=	M('Article')->where(" article_id = '$id' ")->getField("file_url");
//	    if ($old_url != '' && strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false){
//	        //@unlink(ROOT_PATH . $old_url);
//	    }
		$dir		=	"./Public/upload/article/";
		$src		=	M('Article')->where(" article_id = '$id' ")->getField("src");
	    
	    $result		=	M('Article')->where("article_id = '{$id}'")->delete();
	    if ($result){		   
		    if(file_exists($dir . $src)){
		    	@unlink($dir . $src);
		    }		    	
	        M('Comment')->where("comment_type = 1 AND id_value = $id")->delete();
	        M('GoodsArticle')->where("article_id = '{$id}'")->delete();
	        $this->success("操作成功",U("article/article_list"));
	    }
	    else{
	    	$this->success("操作失败",U("article/article_list"));
	    }	
	}
		
	/**
	 * 排序
	 * @param unknown $arr
	 * @param number $parent_id
	 * @param number $lev
	 * @return multitype:number
	 */
	public function catsort($arr,$parent_id = 0,$lev = 1){
		static $list = array();
		foreach ($arr as $v){
			if($v['parent_id'] == $parent_id){
				$v['lev']  = $lev;
				$list[]    = $v;
				$this->catsort($arr,$v['cat_id'],$lev +1);
			}
		}
		return $list;
	}
	
	/***************************** [ Ajax ] ***************************/
	public function articleAjaxTable(){
		$Course             =    new Model('Article');
		$act                =    $_POST['action'];
		
		switch($act){
			case 'add':
				//add code
				break;
			case 'del':
				$id       =    $_POST['id'];
				$result   =    $Course->where("article_id='{$id}'")->delete();
		
				if($result){
					$this->ajaxReturn($result,"操作成功",1);
				}else{
					$this->ajaxReturn($result,"操作失败",0);
				}
				break;
			case 'update':break;
			case 'edit':
				/*修改字段*/				
				$field	=	$_REQUEST['field'];
				$value	=	$_REQUEST['value'];
				$id		=	$_REQUEST['id'];
				$result	=	M('Article')->where("article_id = '{$id}'")->setField($field,$value);
				if($result){
					$this->ajaxReturn(1,$value,1);
				}
				else{
					$this->ajaxReturn(0,"",1);	
				}			
				break;
			case 'change':
				$field         =    $_POST['field'];
				$value         =    $_POST['val'];
				$id            =    $_POST['id'];
				$data[$field]  =    $value;
				//Save Data
				$result        =    $Course->where("id=$id")->save($data);
		
				if($result){
					$this->ajaxReturn($value,"操作成功",1);
				}
				else{
					$this->ajaxReturn(null,"操作成功",0);
				}
				break;
			default:
				//add code
				break;
		}
		
	}
	
	/**
	 * Delete Article
	 */
	public function deleteArt(){
		$Article          =      new Model('Article');
		$id               =      $_POST['id'];
		$con              =      "article_id='".$id."'";
		
		$result           =      $Article->where($con)->delete();
		if($result){
			$this->ajaxReturn($result,"操作成功",1);
		}else{
			$this->ajaxReturn($result,"操作失败",0);
		}		
	}
	
	// get_goods_list
	public function get_goods_list(){
		$filters		=	$_GET['JSON'];
		$GoodsModel		=	new GoodsModel();		
		$datas			=	$GoodsModel->getGoodsList($filters);
		$opt = array();
		foreach ($datas AS $key => $val){
	        $opt[] = array('value' => $val['goods_id'],
	                        'text' => $val['goods_name'],
	                        'data' => $val['shop_price']);
	    }
		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}	
	
	// add_link_goods
	public function add_link_goods(){
		
	    $add_ids 	= 	$_GET['add_ids'];
	    $args 		= 	$_GET['JSON'];
	    $article_id = 	$args[0];	
//	    if ($article_id == 0){
//	        $result		=	M('Article')->field("MAX(article_id)+1 AS article_id")->find();
//	        $article_id	=	$result['article_id'];
//	    }	
	    foreach ($add_ids AS $key => $val){
	        $sql = 'INSERT INTO ' . 'ybr_goods_article' . ' (goods_id, article_id) '.
	               "VALUES ('$val', '$article_id')";
	        M()->query($sql);
	    }
	
	    // 重新载入
	    $ArticleModel	= 	new ArticleModel();	    
	    $arr 			= 	$ArticleModel->get_article_goods($article_id);
	    $opt 			= 	array();
	
	    foreach ($arr AS $key => $val){
	        $opt[] = array('value'  => $val['goods_id'],
	                        'text'  => $val['goods_name'],
	                        'data'  => '');
	    }

		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}
	
	// drop_link_goods
	public function drop_link_goods(){	
	    $drop_goods     = 	$_GET['drop_ids'];
	    $arguments      =	$_GET['JSON'];
	    $article_id     = 	$arguments[0];
	
	    if ($article_id == 0){
	        $result		=	M('Article')->field("MAX(article_id)+1 AS article_id")->find();
	        $article_id	=	$result['article_id'];
	    }
	
	    $sql 			= 	"DELETE FROM " . 'ybr_goods_article'." WHERE article_id = '$article_id' AND goods_id " . Utils::db_create_in($drop_goods);
	   	M()->query($sql);
	   	
	    // 重新载入
	   	$ArticleModel	= 	new ArticleModel();	    
	    $arr 			= 	$ArticleModel->get_article_goods($article_id);
	    $opt 			= 	array();
	
	    foreach ($arr AS $key => $val){
	        $opt[] = array('value'  => $val['goods_id'],
	                        'text'  => $val['goods_name'],
	                        'data'  => '');
	    }		
		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}
	
	// 获得文章列表
	function sql_article_list(){
	  
        $filter 				= 	array();
        $filter['keyword']    	= 	empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1){
            $filter['keyword'] 	= 	$filter['keyword'];
        }
        $filter['cat_id'] 		= 	empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['sort_by']    	= 	empty($_REQUEST['sort_by']) ? 'a.article_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] 	= 	empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where 					= 	'';
        if (!empty($filter['keyword'])){
            $where 				= 	" AND a.title LIKE '%" .$filter['keyword'] . "%'";
        }
        if ($filter['cat_id']){
            $where 				.= 	" AND a." . Utils::get_article_children($filter['cat_id']);
        }	

        /* 获取文章数据 */
        $sql = 'SELECT a.* , ac.cat_name '.
               'FROM ' .'ybr_article'. ' AS a '.
               'LEFT JOIN ' .'ybr_article_cat'. ' AS ac ON ac.cat_id = a.cat_id '.
               'WHERE 1 ' .$where. ' ORDER by '.$filter['sort_by'].' '.$filter['sort_order'];
		return $sql; 
	}
	
	/**
	 * 文章自动发布
	 * 
	 * 
	 */
	public function article_auto(){
		$CommonModel	=	new CommonModel();
		$sql_goodsdb 	=	get_sql_auto_goods();
	    $crons_enable 	= 	$CommonModel->getOne("SELECT enable FROM " . 'ybr_crons' . " WHERE cron_code='ipdel'");
	    $this->assign('crons_enable', $crons_enable);
	    $this->assign('full_page',    1);
	    $this->assign('ur_here',      $_LANG['article_auto']);
	    //$this->assign('goodsdb',      $sql_goodsdb);
			    
		$param = array(
				'result'=>$sql_goodsdb,			//分页用的数组或sql
				'listvar'=>'goodsdb',				//分页循环变量
				'listRows'=>10,							//每页记录数
				//'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'=>'content',	    			//ajax更新内容的容器id，不带#
				'pagesId'=>'page',						//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'=>'Article:goods_auto',		//ajax更新模板
		);	
	    
	    $this->page_article_auto($param);
	    $this->display('goods_auto');
	}
	
	public function page_article_auto($param){		
		extract($param);
		
		//总记录数
		$flag 			= 	is_string($result);
		
		$listvar 		= 	$listvar ? $listvar : 'list';
		$listRows 		= 	$listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows 	= 	($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p 		= 	new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p 		= 	new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= 	" LIMIT {$p->firstRow},{$p->listRows}";
			$voList = 	M()->query($result);			
		} else {
			$voList = 	array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages 		= 	C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		// 格式化数据
		$goodsdb 	= 	array();			
		foreach($voList as $rt){
	    	if (!empty($rt['starttime'])){
	            $rt['starttime'] 	= 	local_date('Y-m-d',$rt['starttime']);
	        }
	        if (!empty($rt['endtime'])){
	            $rt['endtime'] 		= 	local_date('Y-m-d',$rt['endtime']);
	        }
	        $rt['goods_id'] 		= 	$rt['article_id'];
	        $rt['goods_name'] 		= 	$rt['title'];
	        $goodsdb[] 				= 	$rt;
	    }
		$voList						=	$goodsdb;
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * 无刷新修改文章
	 * Enter description here ...
	 */
	public function ajax_article(){
		$ArticleModel		=	new ArticleModel();
		
		$action			=	$_POST['action'];
		$field			=	$_POST['field'];
		$value			=	$_POST['value'];
		$article_id		=	$_POST['id'];
		
		switch($action){
			case 'change':
				
				break;
			case 'edit':
				break;
			case 'del':
				$ids	=	array_filter($_POST['id']);	
				if(empty($ids)){
					$this->ajaxReturn(1,0,1);
				}	
				$result	=	$ArticleModel->delete_article_byids($ids);
				if($result){
					$this->ajaxReturn(1,$ids,1);
				}
				else{
					$this->ajaxReturn(1,$ids,1);
				}				
				break;
			case 'mod':
				break;
			default:
				break;
		}
	}
	
	
	public function ajaxtable(){
		$ArticleModel	=	new ArticleModel();		
		$action			=	$_POST['action'];
		$field			=	$_POST['field'];
		$value			=	$_POST['value'];
		$article_id		=	$_POST['id'];
		
		switch($action){
			case 'change':				
				break;
			case 'edit':
				/* 修改的数据 */
				$datas[$field]	=	$value;				
				$ArticleModel->where("article_id = '{$article_id}'")->save($datas);
				$this->ajaxReturn(1,$value,1);
				break;
			case 'del':
				$ids	=	array_filter($_POST['id']);	
				if(empty($ids)){
					$this->ajaxReturn(1,0,1);
				}	
				$result	=	$ArticleModel->delete_article_byids($ids);
				if($result){
					$this->ajaxReturn(1,$ids,1);
				}
				else{
					$this->ajaxReturn(1,$ids,1);
				}				
				break;
			case 'mod':
				break;
			default:
				break;
		}
	}
	
	
	
	
}